package com.longyiqun.cm.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.*;
import com.longyiqun.cm.CaseManager;
import com.longyiqun.cm.domain.SceneEntity;
import com.longyiqun.cm.domain.TestCaseEntity;
import com.longyiqun.cm.mapper.CasesMapper;
import com.longyiqun.cm.mapper.SceneMapper;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.testng.Assert;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Random;

import static io.restassured.RestAssured.given;

@Service
public class SceneServiceImpl implements SceneService{


    @Autowired
    SceneMapper sceneMapper;

    @Autowired
    CasesMapper casesMapper;

    @Override
    public PageInfo APISelect(){
        PageHelper.startPage(1,1000);
        String sql ="select * from test_case_entity where status = 'on'";
        List<TestCaseEntity> list = sceneMapper.APISelect(sql);
        PageInfo pageInfo = new PageInfo(list);
        return  pageInfo;
    }


    @Override
    public PageInfo findAllScene(int pageIndex, int pageNum,String name,String module,String env){
        PageHelper.startPage(pageIndex, pageNum);
        String sql ="select * from test_scene_entity where eStatus = 'on' and name like '%"+name+"%' and module like '%"+module+"%' and env = '"+env+"' order by dtCreateTime desc";
        List<SceneEntity> list = sceneMapper.FindAllScene(sql);
        PageInfo pageInfo = new PageInfo(list);
        return  pageInfo;
    }

    @Override
    public SceneEntity findOne(String sql){
        return sceneMapper.findOne(sql);
    }


    @Override
    public  PageInfo findAPI(int pageIndex,int pageNum,String sceneID){
        PageHelper.startPage(pageIndex, pageNum);
        List<SceneEntity> list = sceneMapper.FindAllAPI(sceneID);
        PageInfo pageInfo = new PageInfo(list);
        return  pageInfo;
    }


    @Override
    public int updateScene(SceneEntity sceneEntity){
        return sceneMapper.upadteScene(sceneEntity);
    }

    @Override
    public String updateAPI(SceneEntity sceneEntity){
        TestCaseEntity testCaseEntity = sceneMapper.findAPIDetail(sceneEntity.getUrl());
        System.out.println(sceneEntity.getUrl());
        if (testCaseEntity == null){
            return "接口库中无此接口";
        }
        int result = sceneMapper.upadteAPI(sceneEntity);
        if (result>0){
            return "true";
        }else {
            return "false";
        }
    }

    @Override
    public int addScene(SceneEntity sceneEntity){
        return sceneMapper.addScene(sceneEntity);
    }

    @Override
    public String addAPI(SceneEntity sceneEntity){

        TestCaseEntity testCaseEntity = sceneMapper.findAPIDetail(sceneEntity.getUrl());

        if (testCaseEntity == null){
            return "接口库中无此接口";
        }
        String caseID = testCaseEntity.getId().toString();
        sceneEntity.setCaseID(caseID);
        sceneEntity.setMethod(testCaseEntity.getMethod());
        sceneEntity.setChinese(testCaseEntity.getChinese());
        sceneEntity.setName(testCaseEntity.getName());
        sceneEntity.setModule(testCaseEntity.getModule());
        int Result =  sceneMapper.addAPI(sceneEntity);
        if (Result >0){
            int count = Integer.parseInt(sceneMapper.findOne("select count from test_scene_entity where sceneID = "+sceneEntity.getSceneID()).getCount());
            sceneMapper.updateSql("update test_scene_entity set count = " +String.valueOf(count+1)+" where sceneID = "+sceneEntity.getSceneID());
            return "true";
        }else {
            return "false";
        }
    }


    @Override
    public int delAPI(String relationID){
        String sql = "delete  from test_api_entity where relationID ="+relationID;
        String sceneID = sceneMapper.GetsceneID("select sceneID from test_api_entity where relationID="+relationID);

        int Result =  sceneMapper.del(sql);
        int count = Integer.parseInt(sceneMapper.findOne("select count from test_scene_entity where sceneID = "+sceneID).getCount());
        sceneMapper.updateSql("update test_scene_entity set count = " +String.valueOf(count-1)+" where sceneID = "+sceneID);
        return Result;
    }

    @Override
    public int sceneCopy(String sceneID){
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        long stemptime = System.currentTimeMillis();
        String time =  String.valueOf(stemptime/1000);

     SceneEntity Entity = sceneMapper.findOne("select * from test_scene_entity where sceneID="+sceneID);
     String name= time+"--"+Entity.getName();
     Entity.setName(name);
     List<SceneEntity> Entity3 = sceneMapper.FindAllAPI(sceneID); //获取原场景的api
        int count = Entity3.size();
         Entity.setCount(String.valueOf(count));
     int R1 = sceneMapper.addScene(Entity);//新建场景
     if (R1 < 1){
         System.out.println("插入场景失败");
     }
     SceneEntity ID = sceneMapper.findOne("select * from test_scene_entity where name= '"+name+"'");//获取新场景的SceneID


     for (int i = 0; i<Entity3.size();i++){
         SceneEntity t = Entity3.get(i);
         t.setSceneID(ID.getSceneID());
         int result = sceneMapper.addAPI(t);
     }
        return 1;
    }

    @Override
    public String GetCleanSql(String sceneID,String env){
        String sql = sceneMapper.getscript(sceneID);
        return sql;
    }
    @Override
    public String mockScene(String id,String env){
        List<SceneEntity> allCases = sceneMapper.FindAllAPI(id);
        for(int i=0;i< allCases.size();i++){
/*
           String result =  PostScene(allCases.get(i),env);
*/
        }

        return "";
    }
    /*public String  PostScene (SceneEntity c, String env) {
        // 获取Case信息
        String postBody = c.getBody();
        String caseModel = c.getModule();
        String url = sceneMapper.geturl("select url from tbEnvConf where env ="+env);
        String shouldBe = c.getShouldbe();
        String loginName = c.getLoginName();
//        // Log输出
//        YLog.RedGreen("***用例名称: ", c.getChinese());
        YLog.Error("URL: " + url);
//        YLog.GreenRed("模块: ", caseModel);

        login login = new login();
        // 获取登录的Token和UID
        int result = login.loginSet(url, postBody,env,caseModel);
        String tokenAnduid = login.loginGet(loginName, env);
//        String tokenAnduid = "token,22";
        if (!tokenAnduid.equals("")) {

            String token = tokenAnduid.split(",")[0];
            String uid = tokenAnduid.split(",")[1];

            // 获取验签后的BODY体
            JsonObject jsonObject = getBodyWithSign(postBody, token, uid);


            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            JsonParser jp = new JsonParser();

            // 获取Request的Json字符串
            JsonElement jeRequest = jp.parse(jsonObject.toString());
            String prettyJsonRequest = gson.toJson(jeRequest);

            try {
                // 获取response
                final Response response = given().contentType(ContentType.JSON).body(jsonObject.toString()).post(url);

                // 获取JSON返回
                JsonElement jeReturn = jp.parse(response.body().asString());
                String prettyJsonReturn = gson.toJson(jeReturn);

                YLog.MagentYellow("入参: \n", prettyJsonRequest);

                // 获取时长
                final long duration = response.time();
                YLog.BlueBlack("用时: ", (Long.toString(duration) + "ms \n"));
                YLog.BlueBlack("url",c.getUrl());
                // 填充报告
                setAttributeToResult(prettyJsonReturn, prettyJsonRequest, c.getName(), c.getChinese(), url, caseModel, shouldBe);

                // 根据验证字段校验返回值
                verifyResult(shouldBe, jeReturn);

            } catch (Exception ex) {

                // 填充报告
                setAttributeToResult("服务器通信错误, 详细信息: " + ex.getMessage(), prettyJsonRequest, c.getName(), c.getChinese(), url, caseModel, shouldBe);
                Assert.fail(ex.getMessage());
            }
        } else {

            // 填充报告
            setAttributeToResult("登录信息有误, 中断请求", c.getBody(), c.getName(), c.getChinese(), url, caseModel, shouldBe);
            Assert.fail("登录信息有误, 中断请求");
        }
    }*/
}
